package com.itheima.stock.service.Impl;

import com.google.common.base.Strings;
import com.itheima.stock.mapper.SysUserMapper;
import com.itheima.stock.pojo.SysUser;
import com.itheima.stock.service.UserService;
import com.itheima.stock.utils.IdWorker;
import com.itheima.stock.vo.req.LoginReqVo;
import com.itheima.stock.vo.resp.LoginRespVo;
import com.itheima.stock.vo.resp.R;
import com.itheima.stock.vo.resp.ResponseCode;
import org.apache.commons.lang3.RandomStringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.RandomAccess;
import java.util.concurrent.TimeUnit;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public R<LoginRespVo> login(LoginReqVo vo) {
        if (vo==null|| Strings.isNullOrEmpty(vo.getUsername())
                ||Strings.isNullOrEmpty(vo.getPassword())||
                Strings.isNullOrEmpty(vo.getCode())) {
            return R.error(ResponseCode.TOKEN_PAST_DUE.getMessage());
        }
        String o = (String) redisTemplate.opsForValue().get(vo.getRkey());
        if (Strings.isNullOrEmpty(o) || !o.equals(vo.getCode())){
            return R.error(ResponseCode.SYSTEM_VERIFY_CODE_ERROR.getMessage());
        }
        redisTemplate.delete(vo.getRkey());
        SysUser user=sysUserMapper.findByUserName(vo.getUsername());

        if (user==null){
            return R.error(ResponseCode.SYSTEM_USERNAME_NOT_EXISTS.getMessage());
        }
        boolean matches = passwordEncoder.matches(vo.getPassword(), user.getPassword());
        if (!matches){
            return R.error(ResponseCode.SYSTEM_PASSWORD_EXPIRED2.getMessage());
        }
        LoginRespVo respVo = new LoginRespVo();
        BeanUtils.copyProperties(user,respVo);
        return  R.ok(respVo);
    }
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 分布式环境保证生成id唯一
     */
    @Autowired
    private IdWorker idWorker;
    @Override
    public R<Map> generateCaptcha() {
        String s = RandomStringUtils.randomNumeric(4);
        String s1 = String.valueOf(idWorker.nextId());
        redisTemplate.opsForValue().set(s1,s,60, TimeUnit.SECONDS);
        Map<String, String> map = new HashMap<>();
        map.put("rkey",s1);
        map.put("code",s);
        return R.ok(map);
    }
}
